﻿/**  版本信息模板在安装目录下，可自行修改。
* DepartmentType.cs
*
* 功 能： N/A
* 类 名： DepartmentType
*
* Ver    变更日期             负责人  变更内容
* ───────────────────────────────────
* V0.01  2013-4-18 15:57:45   N/A    初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│　此技术信息为本公司机密信息，未经本公司书面同意禁止向第三方披露．　│
*│　版权所有：动软卓越（北京）科技有限公司　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Maticsoft.DBUtility;

namespace DMZS.DAL
{
    /// <summary>
    /// 数据访问类:DepartmentType
    /// </summary>
    public partial class DepartmentType
    {
        public DepartmentType()
        {
        }

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return DbHelperSQL.GetMaxID("ID", "DepartmentType");
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int ID)
        {
            var strSql = new StringBuilder();
            strSql.Append("select count(1) from DepartmentType");
            strSql.Append(" where ID=@ID");
            var parameters = new SqlParameter[] { new SqlParameter("@ID", SqlDbType.Int, 4)
            };
            parameters[0].Value = ID;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(DMZS.Model.DepartmentType model)
        {
            var strSql = new StringBuilder();
            strSql.Append("insert into DepartmentType(");
            strSql.Append("No,Name)");
            strSql.Append(" values (");
            strSql.Append("@No,@Name)");
            strSql.Append(";select @@IDENTITY");
            var parameters = new SqlParameter[] { new SqlParameter("@No", SqlDbType.NVarChar, 50),
                    new SqlParameter("@Name", SqlDbType.NVarChar, 100) };
            parameters[0].Value = model.No;
            parameters[1].Value = model.Name;

            var obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(DMZS.Model.DepartmentType model)
        {
            var strSql = new StringBuilder();
            strSql.Append("update DepartmentType set ");
            strSql.Append("No=@No,");
            strSql.Append("Name=@Name");
            strSql.Append(" where ID=@ID");
            var parameters = new SqlParameter[] { new SqlParameter("@No", SqlDbType.NVarChar, 50),
                    new SqlParameter("@Name", SqlDbType.NVarChar, 100),
                    new SqlParameter("@ID", SqlDbType.Int, 4) };
            parameters[0].Value = model.No;
            parameters[1].Value = model.Name;
            parameters[2].Value = model.ID;

            var rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int ID)
        {
            var strSql = new StringBuilder();
            strSql.Append("delete from DepartmentType ");
            strSql.Append(" where ID=@ID");
            var parameters = new SqlParameter[] { new SqlParameter("@ID", SqlDbType.Int, 4)
            };
            parameters[0].Value = ID;

            var rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string IDlist)
        {
            var strSql = new StringBuilder();
            strSql.Append("delete from DepartmentType ");
            strSql.Append(" where ID in (" + IDlist + ")  ");
            var rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public DMZS.Model.DepartmentType GetModel(int ID)
        {
            var strSql = new StringBuilder();
            strSql.Append("select  top 1 ID,No,Name from DepartmentType ");
            strSql.Append(" where ID=@ID");
            var parameters = new SqlParameter[] { new SqlParameter("@ID", SqlDbType.Int, 4)
            };
            parameters[0].Value = ID;
            var ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public DMZS.Model.DepartmentType DataRowToModel(DataRow row)
        {
            var model = new DMZS.Model.DepartmentType();
            if (row != null)
            {
                if (row["ID"] != null && row["ID"].ToString() != string.Empty)
                {
                    model.ID = int.Parse(row["ID"].ToString());
                }
                if (row["No"] != null)
                {
                    model.No = row["No"].ToString();
                }
                if (row["Name"] != null)
                {
                    model.Name = row["Name"].ToString();
                }
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            var strSql = new StringBuilder();
            strSql.Append("select ID,No,Name ");
            strSql.Append(" FROM DepartmentType ");
            if (strWhere.Trim() != string.Empty)
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            var strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" ID,No,Name ");
            strSql.Append(" FROM DepartmentType ");
            if (strWhere.Trim() != string.Empty)
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            var strSql = new StringBuilder();
            strSql.Append("select count(1) FROM DepartmentType ");
            if (strWhere.Trim() != string.Empty)
            {
                strSql.Append(" where " + strWhere);
            }
            var obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            var strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.ID desc");
            }
            strSql.Append(")AS Row, T.*  from DepartmentType T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }


        /// <summary>
        /// 获得数据列表 扩展
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public DataSet GetListForUIExpand(string strWhere)
        {
            var strSql = @"
select c.ID,c.No,c.Name,isnull(r.ID,0) RelID,isnull(r.ParentID,0) ParentID, 
    isnull(p.No,'') ParentNo, isnull(p.Name,'') ParentName 
from DepartmentType c 
left join DepartmentTypeRel r on c.ID=r.ChildID 
left join DepartmentType p on p.ID=r.ParentID 
";
            if (strWhere.Trim() != string.Empty)
            {
                strSql += " where " + strWhere;
            }
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取数据行
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public DataTable GetRecordByID(int ID)
        {
            var strSql = @"
select c.ID,c.No,c.Name,isnull(r.ID,0) RelID,isnull(r.ParentID,0) ParentID, 
    isnull(p.No,'') ParentNo, isnull(p.Name,'') ParentName 
from DepartmentType c 
left join DepartmentTypeRel r on c.ID=r.ChildID 
left join DepartmentType p on p.ID=r.ParentID 
where c.ID=@ID
";
            var parameters = new SqlParameter[] { new SqlParameter("@ID", SqlDbType.Int) };
            parameters[0].Value = ID;

            var ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0];
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 增加一条数据 扩展
        /// 返回-1001:编号重复; 
        /// </summary>
        public int AddExpand(DMZS.Model.DepartmentType model, int ParentID)
        {
            var strSql = @"
declare @typeNoCount int, @childID bigint 
select @typeNoCount=count(1) from DepartmentType where No=@No 
if @typeNoCount>0 begin select -1001 return end 

begin tran 
    insert into DepartmentType(No,Name) values (@No,@Name)
    select @childID=@@IDENTITY
    if  @ParentID<>0
        insert into DepartmentTypeRel(ParentID,childID) values (@ParentID,@childID)
if @@error<>0
begin
	rollback tran
	select -1000
end
else 
begin
	commit tran
	select @childID
end";
            var parameters = new SqlParameter[] { new SqlParameter("@No", SqlDbType.NVarChar, 50),
                    new SqlParameter("@Name", SqlDbType.NVarChar, 100),
                    new SqlParameter("@ParentID", SqlDbType.Int) };

            parameters[0].Value = model.No;
            parameters[1].Value = model.Name;
            parameters[2].Value = ParentID;

            var obj = DbHelperSQL.GetSingle(strSql, parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 获取第一级子项个数
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int GetChildrenCount(int ID)
        {
            var sqlStr = "select count(1) from DepartmentTypeRel where ParentID=" + ID.ToString();
            var result = DbHelperSQL.GetSingle(sqlStr);
            if (result == null)
            {
                return -1;
            }
            else
            {
                return Convert.ToInt32(result);
            }
        }
        /// <summary>
        /// 删除一条数据,及其子级
        /// </summary>
        public bool DeleteExpand(int ID)
        {
            var strSql = @"
begin tran 
delete from DepartmentType where ID=@ID
delete from DepartmentTypeRel where ChildID=@ID
if @@error<>0
begin
    rollback tran
    select -1000
end else begin
    commit tran
    select 1000
end ";

            var parameters = new SqlParameter[] { new SqlParameter("@ID", SqlDbType.Int)

            };
            parameters[0].Value = ID;

            var ds = DbHelperSQL.Query("select ChildID from DepartmentTypeRel where ParentID=" + ID.ToString());

            if (ds == null || ds.Tables.Count == 0)
            {
                return false;
            }
            var success = true;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                success = success && DeleteExpand(Convert.ToInt32(row["ChildID"]));
            }

            var result = DbHelperSQL.GetSingle(strSql, parameters);
            if (result == null || Convert.ToInt32(result) == -1000)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 获取数据行
        /// </summary>
        /// <param name="TypeNo"></param>
        /// <returns></returns>
        public DataRow GetRecordByNo(string TypeNo)
        {
            var strSql = @"
select c.ID,c.No,c.Name,isnull(r.ID,0) RelID,isnull(r.ParentID,0) ParentID, 
    isnull(p.No,'') ParentNo, isnull(p.Name,'') ParentName 
from DepartmentType c 
left join DepartmentTypeRel r on c.ID=r.ChildID 
left join DepartmentType p on p.ID=r.ParentID 
where c.No=@No
";
            var parameters = new SqlParameter[] { new SqlParameter("@No", SqlDbType.NVarChar, 50) };
            parameters[0].Value = TypeNo;

            var ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0];
            }
            else
            {
                return null;
            }
        }
    }
}

